<?php

class CapchaController extends Controller
{

    public function actionUpload() {
        $mac = Yii::app()->request->getParam('mac');
        $accName = Yii::app()->user->getState("accName");
        $siteId = Yii::app()->request->getParam('siteId');
        $allowed = array('jpg', 'jpeg', 'png', 'gif');

        if(isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $filesize = filesize($_FILES['image']['tmp_name']);

            if(in_array(strtolower($extension), $allowed)){
                if (($filesize / 1048576) <= 3) {
                    $accoutDao = new AccountDAO();
                    $accounInfo = $accoutDao->findAccountByMacAndSiteId($mac, $siteId);
                    $accoutId = isset($accounInfo['account_id']) ? $accounInfo['account_id'] : "-1";

                    $capchaDao = new CapchaDAO();
                    $capchaId = $capchaDao->insert($accoutId, $siteId, $extension);
                    $dirCaptcha = APP_ROOT_DIR . Constants::DIR_CAPTCHA . $siteId;

                    if (!is_dir($dirCaptcha)) {
                        mkdir($dirCaptcha);
                    }

                    $newPath = $dirCaptcha . '/' . $capchaId . '.' . $extension;

                    if(move_uploaded_file($_FILES['image']['tmp_name'], $newPath)) {
                        $this->_sendAjaxResponse(json_encode(array('status' => Constants::RESPONSE_SUCCESS, 'capchaId' => $capchaId)));
                    }
                }
            }
        }

        $this->_sendAjaxResponse(json_encode(array('status' => Constants::RESPONSE_ERROR)));
    }


    public function actionContent() {
        $capchaId = Yii::app()->request->getParam('capchaId');
        $capchaDao = new CapchaDAO();

        $capchaInfo = $capchaDao->findById($capchaId);

        if ($capchaInfo && $capchaInfo['content']) {
            $this->_sendAjaxResponse(json_encode(array('status' => Constants::RESPONSE_SUCCESS, 'content' => $capchaInfo['content'])));
        } else {
            $this->_sendAjaxResponse(json_encode(array('status' => Constants::RESPONSE_ERROR)));
        }
    }


}